import socket

from utils.logger_config import get_logger_config

from .nacos_config import NacosConfig
from .nacos_service import NacosService


class NacosManager:
    """Nacos服务管理器，封装Nacos相关操作"""

    def __init__(self, config):
        """
        初始化Nacos管理器

        Args:
            config: 配置对象，包含Nacos相关配置
        """
        self.config = config
        self.logger = get_logger_config(name="nacos_manager").get_logger()
        self.nacos_service = None
        self.port = config.get("service.port", 5555)

        # 初始化Nacos服务
        if config.get("nacos.enabled", True):
            nacos_config = NacosConfig(
                server_addr=config.get("nacos.server_addr", "192.168.3.220:8848"),
                namespace=config.get("nacos.namespace", "public"),
                service_name=config.get("service.name", "rongmei-media-service-zdl"),
                group_name=config.get("nacos.group", "DEFAULT_GROUP"),
            )
            self.nacos_service = NacosService(nacos_config)
        else:
            self.logger.info("Nacos服务已禁用")

    def register(self):
        """注册服务到Nacos"""
        if not self.nacos_service or not self.config.get("nacos.enabled", True):
            self.logger.info("Nacos服务注册已禁用")
            return

        # 测试Nacos连接
        self.logger.info(f"正在测试Nacos连接: {self.config.get('nacos.server_addr')}")
        try:
            self._test_nacos_connection()
        except Exception as e:
            self.logger.error(f"测试Nacos连接时出错: {str(e)}")

        # 注册服务
        metadata = self.config.get(
            "nacos.metadata",
            {
                "version": "1.0.0",
                "services": "face-feature,speech-recognition",
                "description": "媒体信息处理服务",
            },
        )
        success = self.nacos_service.register_service(port=self.port, metadata=metadata)
        if success:
            # 启动心跳
            self.nacos_service.start_heartbeat(port=self.port)
            self.logger.info("成功注册到Nacos服务发现系统")
        else:
            self.logger.warning("注册到Nacos失败，将继续尝试...")

    def deregister(self):
        """从Nacos注销服务"""
        if self.nacos_service:
            self.nacos_service.stop_heartbeat()
            success = self.nacos_service.deregister_service(port=self.port)
            if success:
                self.logger.info("成功从Nacos注销服务")
            else:
                self.logger.warning("从Nacos注销服务失败")

    def _test_nacos_connection(self):
        """测试Nacos连接"""
        nacos_addr = self.config.get("nacos.server_addr", "192.168.3.220:8848")
        if "://" in nacos_addr:
            nacos_addr = nacos_addr.split("://")[1]

        host, port_str = nacos_addr.split(":")
        port = int(port_str)

        # 尝试TCP连接
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        result = s.connect_ex((host, port))
        s.close()

        if result == 0:
            self.logger.info(f"Nacos服务器连接成功: {host}:{port}")
        else:
            self.logger.error(f"无法连接到Nacos服务器: {host}:{port}, 错误码: {result}")
            raise ConnectionError(f"无法连接到Nacos服务器: {host}:{port}")
